SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN TRANSACTION;
BEGIN TRY
    -- 检查库存
    DECLARE @stock INT;
    SELECT @stock = Stock 
    FROM Products 
    WHERE ProductID = 202;

    IF @stock >= 1
    BEGIN
        -- 扣减库存
        UPDATE Products 
        SET Stock = Stock - 1 
        WHERE ProductID = 202;

        -- 生成订单
        INSERT INTO Orders (ProductID, UserID) 
        VALUES (202, 'user123');
    END
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION;
    THROW;
END CATCH;
